// 青云教育系统登录页面JavaScript
class LoginManager {
    constructor() {
        this.messageTimer = null; // 初始化消息定时器
        this.init();
    }

    init() {
        this.bindEvents();
        this.setupLoginCode();
    }

    bindEvents() {
        // 登录表单提交
        const loginForm = document.getElementById('loginForm');
        loginForm.addEventListener('submit', (e) => this.handleLogin(e));

        // 登录码刷新按钮（显示提示信息）
        const refreshCodeBtn = document.getElementById('refreshCode');
        refreshCodeBtn.addEventListener('click', () => this.showLoginCodeInfo());

        // 输入框焦点事件
        const inputs = document.querySelectorAll('input');
        inputs.forEach(input => {
            input.addEventListener('focus', () => this.handleInputFocus(input));
            input.addEventListener('blur', () => this.handleInputBlur(input));
        });
    }

    handleInputFocus(input) {
        input.parentElement.classList.add('focused');
    }

    handleInputBlur(input) {
        if (!input.value) {
            input.parentElement.classList.remove('focused');
        }
    }

    setupLoginCode() {
        // 设置登录码按钮显示为"帮助"
        const refreshBtn = document.getElementById('refreshCode');
        refreshBtn.textContent = '帮助';
        refreshBtn.style.fontFamily = 'inherit';
        refreshBtn.style.fontWeight = 'normal';
        refreshBtn.style.letterSpacing = 'normal';
    }

    showLoginCodeInfo() {
        this.showMessage('登录码是系统预定义的内部代码，请联系管理员获取', 'info');
    }

    validateForm() {
        const account = document.getElementById('account').value.trim();
        const password = document.getElementById('password').value.trim();
        const code = document.getElementById('code').value.trim();

        // 清除之前的错误信息
        this.clearMessages();

        if (!account) {
            this.showMessage('请输入账号', 'error');
            document.getElementById('account').focus();
            return false;
        }

        if (!password) {
            this.showMessage('请输入密码', 'error');
            document.getElementById('password').focus();
            return false;
        }

        if (!code) {
            this.showMessage('请输入登录码', 'error');
            document.getElementById('code').focus();
            return false;
        }

        return true;
    }

    clearMessages() {
        const messageEl = document.getElementById('message');
        messageEl.style.display = 'none';
        messageEl.textContent = '';
        messageEl.className = 'message';
        
        // 清除定时器
        if (this.messageTimer) {
            clearTimeout(this.messageTimer);
        }
    }

    async handleLogin(e) {
        e.preventDefault();

        if (!this.validateForm()) {
            return;
        }

        const loginBtn = document.querySelector('.login-btn');
        const originalText = loginBtn.textContent;
        
        // 显示加载状态
        loginBtn.classList.add('loading');
        loginBtn.textContent = '登录中...';

        try {
            const formData = {
                account: document.getElementById('account').value.trim(),
                password: document.getElementById('password').value.trim(),
                code: document.getElementById('code').value.trim()
            };

            // 调用后端登录接口
            const response = await this.callLoginAPI(formData);
            console.log('登录响应:', response);
            
            if (response && response.success) {
                // 保存数据（token或用户对象）
                try {
                    if (response.data) {
                        console.log('准备存储用户信息:', response.data);
                        localStorage.setItem('userInfo', JSON.stringify(response.data));
                        
                        // 验证存储是否成功
                        const storedData = localStorage.getItem('userInfo');
                        if (storedData) {
                            const parsedData = JSON.parse(storedData);
                            console.log('存储成功，验证数据:', parsedData);
                            console.log('Token值:', parsedData.token);
                            
                            if (!parsedData.token) {
                                console.error('警告：存储的数据中没有token字段！');
                            }
                        } else {
                            console.error('存储失败：localStorage中没有找到数据');
                        }
                    } else {
                        console.error('响应中没有data字段');
                    }
                } catch (error) {
                    console.error('存储用户信息时发生错误:', error);
                }
                
                // 延迟跳转，确保localStorage写入完成
                setTimeout(() => {
                    const target = 'index.html';
                    console.log('登录成功，跳转到:', target);
                    window.location.href = target;
                }, 100);
                
                // 兜底跳转
                setTimeout(() => {
                    if (!/index\.html/.test(window.location.href)) {
                        window.location.assign('index.html');
                    }
                }, 500);
                return;
            } else {
                // 显示后端返回的具体错误信息
                const errorMsg = (response && response.errorMsg) ? response.errorMsg : '登录失败，请重试';
                this.showMessage(errorMsg, 'error');
                
                // 登录失败时清空登录码输入框
                document.getElementById('code').value = '';
                
                if (errorMsg.includes('登录码') || errorMsg.includes('验证码')) {
                    console.log('登录码错误，请检查输入');
                }
            }
        } catch (error) {
            console.error('登录错误:', error);
            let errorMessage = '网络错误，请检查网络连接';
            
            if (error.message.includes('Failed to fetch')) {
                errorMessage = '无法连接到服务器，请检查网络或联系管理员';
            } else if (error.message.includes('HTTP error')) {
                errorMessage = '服务器响应错误，请稍后重试';
            }
            
            this.showMessage(errorMessage, 'error');
        } finally {
            // 恢复按钮状态
            loginBtn.classList.remove('loading');
            loginBtn.textContent = originalText;
        }
    }

    async callLoginAPI(formData) {
        // 通过网关调用认证服务
        const apiUrl = '/user/login';
        
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(formData)
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        return await response.json();
    }

    handleLoginSuccess(response) {
        // 已改为在 handleLogin 中直接跳转，此方法保留兼容
        try {
            if (response && response.data) {
                localStorage.setItem('userInfo', JSON.stringify(response.data));
            }
        } catch (_) {}
        window.location.href = 'index.html';
    }

    showMessage(message, type = 'info') {
        const messageEl = document.getElementById('message');
        
        // 清除之前的定时器
        if (this.messageTimer) {
            clearTimeout(this.messageTimer);
        }
        
        // 立即显示消息
        messageEl.textContent = message;
        messageEl.className = `message ${type}`;
        messageEl.style.display = 'block';
        
        // 设置新的定时器，5秒后自动隐藏
        this.messageTimer = setTimeout(() => {
            messageEl.style.display = 'none';
        }, 5000);
    }

    // 工具方法：防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new LoginManager();
});

// 添加一些额外的交互效果
document.addEventListener('DOMContentLoaded', () => {
    // 添加输入框动画效果
    const inputs = document.querySelectorAll('.form-group input');
    
    inputs.forEach(input => {
        input.addEventListener('input', (e) => {
            if (e.target.value) {
                e.target.parentElement.classList.add('has-value');
            } else {
                e.target.parentElement.classList.remove('has-value');
            }
        });
    });

    // 添加键盘快捷键支持
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && e.ctrlKey) {
            document.getElementById('loginForm').dispatchEvent(new Event('submit'));
        }
    });

    // 添加表单验证提示
    const form = document.getElementById('loginForm');
    form.addEventListener('input', (e) => {
        if (e.target.validity.valid) {
            e.target.classList.remove('invalid');
            e.target.classList.add('valid');
        } else {
            e.target.classList.remove('valid');
            e.target.classList.add('invalid');
        }
    });
}); 